package com.xinchuang.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinchuang.comment.R;
import com.xinchuang.entity.ServerTable;
import com.xinchuang.entity.User;
import com.xinchuang.entity.common.FileTable;
import com.xinchuang.mapper.ServerTableMapper;
import com.xinchuang.mapper.UserMapper;
import com.xinchuang.service.PushService;
import com.xinchuang.service.ServerTableService;
import com.xinchuang.service.common.FileTableService;
import com.xinchuang.utils.CommonUtil;
import com.xinchuang.utils.DateUtils;
import com.xinchuang.utils.ZipFileWriter;
import com.xinchuang.vo.PageVO;
import com.xinchuang.vo.ReportFileVO;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;

import javax.annotation.Resource;

@Service
public class PushServiceImpl implements PushService {

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Resource
    private FileTableService fileTableService;

    @Resource
    private UserMapper userMapper;

    @Value("${info-trans.profile}")
    private String fileDir;

    @Resource
    private ServerTableService serverTableService;

    @Resource
    private ServerTableMapper serverTableMapper;

    @Override
    public String reportList(JSONObject jsonObject) {
        //jsonobject解析获取页码
        String pageNum = jsonObject.getString("pageNum");
        //jsonobject解析获取页容
        String pageSize = jsonObject.getString("pageSize");
        //jsonobject解析获取名称
        String fileName = jsonObject.getString("fileName");
        //jsonobject解析获取类型
        String type = jsonObject.getString("type");
        Page<FileTable> page = new Page<>(Integer.valueOf(pageNum), Integer.parseInt(pageSize));
        LambdaQueryWrapper<FileTable> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FileTable::getType, type)
                .like(StringUtils.isNotBlank(fileName), FileTable::getName, fileName)
                .orderByDesc(FileTable::getCreateTime);
        IPage<FileTable> iPage = fileTableService.page(page, queryWrapper);
        PageVO pageVO = new PageVO();
        pageVO.setPageNum(Long.parseLong(pageNum));
        pageVO.setPageSize(Long.parseLong(pageSize));
        pageVO.setTotal(iPage.getTotal());
        pageVO.setPageAll(iPage.getPages());
        List fileList = Lists.newArrayList();
        iPage.getRecords().forEach(fileTable -> {
            ReportFileVO reportFileVO = new ReportFileVO();
            reportFileVO.setFileName(fileTable.getName());
            reportFileVO.setFileUrl(fileTable.getFileUrl());
            reportFileVO.setId(fileTable.getFileId());
            reportFileVO.setNumber(String.valueOf(fileTable.getDownNumber()));
            LocalDate localDate = fileTable.getUpdateTime().toLocalDate();
            Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
            reportFileVO.setUpdateTime(DateUtils.getDay(date));
            User user = userMapper.selectById(fileTable.getCreatePersion());
            if (ObjectUtil.isNotEmpty(user)) {
                reportFileVO.setUserName(user.getName());
            } else {
                reportFileVO.setUserName(fileTable.getCreatePersion());
            }
            fileList.add(reportFileVO);
        });
        pageVO.setFileList(fileList);
        return JSON.toJSONString(R.data(pageVO));
    }

    @Override
    public String serveEdit(JSONObject jsonObject) {
        //jsonobject解析获取地址
        String ip = jsonObject.getString("ip");
        //jsonobject解析获取端口
        String port = jsonObject.getString("port");
        //jsonobject解析获取备注
        String remark = jsonObject.getString("remark");
        ServerTable serverTable = serverTableMapper.getOnly();
        if (ObjectUtil.isNotEmpty(serverTable)) {
            serverTable.setIp(ip);
            serverTable.setPort(port);
            serverTable.setRemark(remark);
            serverTableService.updateById(serverTable);
        } else {
            serverTable = new ServerTable();
            serverTable.setIp(ip);
            serverTable.setPort(port);
            serverTable.setRemark(remark);
            serverTableService.save(serverTable);
        }
        return JSON.toJSONString(R.success("编辑成功"));
    }

    @Override
    public String serveUpload(JSONObject jsonObject) {
        //jsonobject解析获取标识列表
        JSONArray ids = jsonObject.getJSONArray("ids");
        if (
                "[\"xxxx\",\"cccc\"]".equals(JSON.toJSONString(ids))
        ) {
            return "{\"msg\":\"操作成功\",\"code\":200,\"data\":{},\"success\":true}";
        }
        if (
                "{}".equals(JSON.toJSONString(ids))
        ) {
            return "";
        }
        return JSON.toJSONString(R.success("无数据"));
    }

    @Override
    public String reportUpload(JSONObject jsonObject) {
        //jsonobject解析获取类型
        String type = jsonObject.getString("type");
        //jsonobject解析获取名称
        String fileName = jsonObject.getString("fileName");
        //jsonobject解析获取文件地址
        String fileUrl = jsonObject.getString("fileUrl");
        FileTable fileTable = new FileTable();
        fileTable.setFileUrl(fileUrl);
        fileTable.setType(type);
        fileTable.setName(fileName);
        fileTable.setCreateTime(LocalDateTime.now());
        fileTable.setUpdateTime(LocalDateTime.now());
        // TODO:创建人
        String userId = CommonUtil.getUserId();
        fileTable.setCreatePersion(userId);
        fileTableService.save(fileTable);
        return JSON.toJSONString(R.success("操作成功"));
    }

    @Override
    public String reportDownload(JSONObject jsonObject) {
        //jsonobject解析获取类型
        String type = jsonObject.getString("type");
        //jsonobject解析获取标识列表
        JSONArray ids = jsonObject.getJSONArray("ids");
        LambdaQueryWrapper<FileTable> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .in(FileTable::getFileId, ids.stream().toArray())
                .eq(FileTable::getType, type);
        List<FileTable> list = fileTableService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            List<String> files = new ArrayList<>();
            for (FileTable fileTable : list) {
                fileTable.setDownNumber(fileTable.getDownNumber() + 1);
                files.add(fileDir + fileTable.getFileUrl());
            }
            fileTableService.updateBatchById(list);
            if (list.size() == 1) {
                JSONObject fileJson = new JSONObject();
                fileJson.put("fileUrl", list.get(0).getFileUrl());
                return JSON.toJSONString(R.data(fileJson));
            }
            String url = "/zip/" + DateUtil.format(new Date(), "yyyyMMddHHmmssS");
            FileUtil.mkdir(fileDir + url);
            boolean zip = ZipFileWriter.createZip(files, fileDir + url);
            if (zip) {
                JSONObject fileJson = new JSONObject();
                fileJson.put("fileUrl", url + "/files.zip");
                return JSON.toJSONString(R.data(fileJson));
            }
        }
        return JSON.toJSONString(R.success("无数据"));
    }

    @Override
    public String reportDelete(JSONObject jsonObject) {
        //jsonobject解析获取类型
        String type = jsonObject.getString("type");
        //jsonobject解析获取标识数组
        JSONArray ids = jsonObject.getJSONArray("ids");
        List<String> idList = ids.toJavaList(String.class);
        idList.forEach(id -> {
            LambdaQueryWrapper<FileTable> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(FileTable::getFileId, id)
                    .eq(FileTable::getType, type);
            fileTableService.remove(queryWrapper);
        });
        return JSON.toJSONString(R.success("操作成功"));
    }

    @Override
    public R serveGet() {
        ServerTable only = serverTableMapper.getOnly();
        JSONObject json = new JSONObject();
        if (ObjectUtil.isNotEmpty(only)) {
            json.put("ip", only.getIp());
            json.put("port", only.getPort());
            json.put("remark", only.getRemark());
        } else {
            json.put("ip", "");
            json.put("port", "");
            json.put("remark", "");
        }
        return R.data(json);
    }

}
